package com.wlc.thread;

import lombok.Data;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.logging.Logger;

/**
 * @author 王立朝
 * @date 2022/2/17
 * @description: CountDownLatch做多任务并行处理的工具类
 */
@Data
public class BatchHandleExecutorUtil {


    private CountDownLatch latch;

    private Executor executor;

    /***
     * 构造一个批处理工具
     * @param size 任务数
     * @param executor 线程池由业务指定
     * @return
     */
    public static BatchHandleExecutorUtil init(int size, Executor executor) {
        BatchHandleExecutorUtil batchHandleExecutor = new BatchHandleExecutorUtil();
        CountDownLatch latch = new CountDownLatch(size);
        batchHandleExecutor.setLatch(latch);
        batchHandleExecutor.setExecutor(executor);
        return batchHandleExecutor;
    }

    public void execute(Runnable task) {
        executor.execute(() -> {
            try {
                task.run();
                System.out.println("hello");
            } catch (Exception e) {

                System.out.printf("BatchHandleExecutor.execute error.", e);
            } finally {
                latch.countDown();
            }
        });
    }

    public void await() {
        try {
            latch.await();
        } catch (Exception e) {
            System.out.printf("BatchHandleExecutor.await error.", e);
        }
    }


}
